<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.cellEncoding"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="单元编码"
        ></el-input>
        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.productLine"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="请输入产品线"
        ></el-input>
        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.movement"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="请输入动作"
        ></el-input>
        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.materialClass"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="请输入物料类别"
        ></el-input>
        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.property1"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="请输入属性1"
        ></el-input>
        <el-input
              @keyup.enter.native="getData"
              clearable
              v-model="listQuery.property2"
              style="width: 150px;margin-right:15px;"
              class="filter-item"
              placeholder="请输入属性2"
        ></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
    </div>

    <!-- table 表格 -->
    <el-table
      :data="tableInfo"
      element-loading-text="给我一首歌的时间"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="单元编码" prop="cellEncoding" align="center" />
      <el-table-column label="产品线" prop="productLine" align="center" />
      <el-table-column label="动作" prop="movement" align="center" />
      <el-table-column
        label="动作缩写"
        prop="movementAbbreviation"
        align="center"
      />
      <el-table-column label="物料类别" prop="materialClass" align="center" />
      <el-table-column
        label="物料类别缩写"
        prop="materialClassAbbreviation"
        align="center"
      />
      <el-table-column label="属性1" prop="property1" align="center" />
      <el-table-column
        label="缩写1"
        prop="property1Abbreviation"
        align="center"
      />
      <el-table-column label="属性2" prop="property2" align="center" />
      <el-table-column
      label="缩写2"
      prop="property2Abbreviation"
      align="center"
      />
      <el-table-column label="单价" prop="price" align="center" >
        <template slot-scope="scope" >
            {{  Math.round(scope.row.price * 1000) / 1000 }}
          </template>
      </el-table-column>
      <el-table-column label="单元时间（秒）" prop="time" align="center"/>
      <el-table-column label="是否关联" prop="isRelevance" align="center"/>
      <el-table-column label="备注" prop="remark" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" />
      <el-table-column  label="操作" align="center" v-if="userInfo.roleId == 0 || userInfo.roleId == 14">
          <template slot-scope="scope" >
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
    </el-table>
    
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5, 10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>
    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>
    <el-button type="success" size="small" @click="getExcelList">下载Excel模板</el-button>
    <el-divider></el-divider>

    <el-upload
      class="upload-demo"
      ref="upload"
      :action="action"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :headers="httpHeader"
      :file-list="fileList"
      :auto-upload="false"
      v-if="userInfo.roleId != 37"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button
        style="margin-left: 10px"
        size="small"
        type="success"
        @click="submitUpload"
        >上传到服务器</el-button
      >
      <div slot="tip" class="el-upload__tip">
        将下载好的Excel表单从此处上传到服务器
      </div>
    </el-upload>
  </div>
</template>
  
  <script>  
import { config_ems_Find,delEcnChange } from "../../api/staffscan";
import { uploadURL } from "@/utils/baseURL";
export default {
  name: "emsPrice",
  data() {
    return {
        loading: false,
      httpHeader: {
        Authorization: "",
      },
      fileList: [],
      action: uploadURL + "/back/money-config-ems/moneyConfigEmsExcel",
      listQuery: {
        page: 1,
        limit: 10,
      },
      total: "", //返回信息总数
      formLabelWidth: "100px", //弹框内部组件的宽度设定
      dialogFormVisible: false, //变更弹窗显现条件
      modifyform: {
        //ECN变更表单
        ecnChangeId: "", //只显示给用户看，input框为disable
        version: "",
        produceName: "",
        ecnDesc: "",
      },
      tableInfo: "", //table表单内容
      userInfo: this.$store.state.user.userInfo,
    };
  },
  methods: {
    // 下载模板表单
    getExcelList() {
        window.open('http://180.76.113.62:8110/image/portrait/example1.rar')
      },
      // 导出excel
    async hExportExcel() {
      this.loading = true
      let query = Object.assign({},this.listQuery)
      query.page = 1
      query.limit = 10000
      console.log('%c导出excel传的参数query:','color:green;font-size:16px;')
      console.log(query)
      // if(this.userInfo.departmentName == '喷涂车间') { query.isSpray = true }
      let arr = await config_ems_Find(query)
      if(arr.code != '1') return  this.$message.error(arr.msg)
      const { header, data } = this.transformDat(this.setSort(arr.data.list))
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: 'ems单价维护-excel', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
        })
      })
      this.loading = false
    },
    transformDat(res) {
      const mapInfo = {
        cellEncoding: '单元编码',
        productLine: '产品线',
        movement: '动作',
        movementAbbreviation: '动作缩写',
        materialClass: '物料类别',
        materialClassAbbreviation: '物料类别缩写',
        property1: '属性1',
        property1Abbreviation: '缩写1',
        property2: '属性2',
        property2Abbreviation: '缩写2',
        price: '单价',
        isRelevance: '是否关联',
        time: '单元时间（秒）',
        remark: '备注',
        createTime: '创建时间'
      }
      // 对data进行格式化
      // 取出所有的属性名
      const props = Object.keys(res[0]) // ['id','']
      console.log(props)
      // 将属性名从英文转为中文
      const header = props.map(zhkey => mapInfo[zhkey])
      console.log('中文的表头', header)
      // const data=[['xxxx','总裁办'，'13800000']]
      const data = res.map(obj => Object.values(obj))
      console.log(data)
      return { header, data }
    },
     // 排序函数
     setSort(arr){
      let newArr = JSON.parse(JSON.stringify(arr))
      let arr1 = []
      newArr.forEach((item)=>{
        let obj = {
            cellEncoding: item.cellEncoding,
            productLine: item.productLine,
            movement: item.movement,
            movementAbbreviation: item.movementAbbreviation,
            materialClass: item.materialClass,
            materialClassAbbreviation: item.materialClassAbbreviation,
            property1: item.property1,
            property1Abbreviation: item.property1Abbreviation,
            property2: item.property2,
            property2Abbreviation: item.property2Abbreviation,
            price: item.price,
            time: item.time,
            isRelevance: item.isRelevance,
            remark: item.remark,
            createTime: item.createTime,
      }
      arr1.push(obj)
      })
      return arr1
    },
    submitUpload() {
      // this.httpHeader.Authorization = this.dealCookie(document.cookie);
      this.httpHeader.Authorization = this.$store.state.user.token,
      this.$refs.upload.submit();
    },
    handleSuccess(response) {
      console.log(response);
      const result = response.code;
      const errMsg = response.msg;
      //  this.uploadLoading = false
      //  this.showfilelist = true
      //  this.uploadTip = '上传到服务器'
      this.$refs["upload"].clearFiles();
      if (result == "1") {    
        this.$message({
          type: "success",
          message: errMsg,
        });
        this.handleFilter();
        // this.resultData = result.data
      } else {
        this.$message({
          type: "error",
          message: errMsg,
        });
      }
    },
    // cookies的处理函数
    dealCookie(value) {
      const cookieArr = value.split("=");
      // cookieArr[2]测试服使用
      return cookieArr[1];
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    getData() {
      this.listQuery.page = 1;
      this.handleFilter();
    },
    // 搜索按钮绑定的函数
    // 获取table表单数据与数据总数
    async handleFilter() {
      let query = Object.assign({}, this.listQuery);
      let { data } = await config_ems_Find(query);
      this.tableInfo = data.list;
      this.total = data.count;
    },
    //删除ECN一行信息
    handleDelete(index, row) {
      this.$confirm("这将会永久删除该行数据，是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
          await delEcnChange({ cellEncoding: row.cellEncoding });
          this.tableInfo.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功",
          });
        }).catch(() => {
          this.$message({ 
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // table表单下方的页码组件改变每页显示的数据条数
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.handleFilter();
    },
    // table表单下方的页码组件改变页面
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.handleFilter();
    },
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter();
  },
};
</script>
  
  <style>
</style>